/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  Author: g0tsu
 *  Email:  g0tsu at dnmx.0rg
 */

#include <libcaptcha.h>
#include <global.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <errno.h>
#include <utf8.h>

#define LC_DEFAULT_LETTER_PADDING 3

lc_arrGlyph * lc_str_to_arr(lc_fontBuffer * font, const char *str,
    const int line_height, const int delta) {

  lc_arrGlyph * arr;
  lc_bmpGlyph *item;

  int i = 0, counter = 0, lh = 0,
      xline = LC_DEFAULT_LETTER_PADDING,
      hline = LC_DEFAULT_LETTER_PADDING;

  int str_len = u8_strlen((char *)str);
  uint8_t bytes[str_len];
  uint32_t c;

  if ((arr = malloc(sizeof(*arr))) == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  arr->type = LC_TYPE_ARR;
  arr->size = str_len;

  if ((arr->items = malloc(sizeof(*item) * arr->size)) == NULL) {
    errno = ENOMEM;
    return NULL;
  }

  if (delta != 0) {
    lc_random_bytes(&bytes, str_len);
  }

  while((c = u8_nextchar((char *)str, &i))) {
    if (delta != 0) {
      lh = bytes[counter] % delta;
      lh = lh < line_height ? line_height : lh;
    } else {
      lh = line_height;
    }

    item = lc_create_glyph(font, c, lh);

    /*
     * Make a predefined offset
     *   _____________
     *  |   |   |   | ...
     *   -------------
     */
    item->y = 0;
    item->x = xline;
    xline += item->w + LC_DEFAULT_LETTER_PADDING;
    hline = MAX(hline, item->h);

    if (!item) {
      lc_free(arr);
      return NULL;
    }

    arr->items[counter++] = item;
  }

  arr->h = hline + LC_DEFAULT_LETTER_PADDING;

  for (int i = 0; i < arr->size; i++) {
    arr->items[i]->y = (hline - arr->items[i]->h);
  }

  lc_recalculate_arr(arr);

  return arr;
}

